class RoleplayApp {
    constructor() {
        this.currentPersona = null;
        this.sessionId = null;
        this.stompClient = null;
        this.isRecording = false;
        this.mediaRecorder = null;
        this.audioChunks = [];
        this.isReceivingResponse = false; // 标记是否正在接收流式响应
        
        // 诊断信息
        this.logDiagnostics();
        
        this.initializeElements();
        this.bindEvents();
        this.loadPersonas();
    }
    
    logDiagnostics() {
        console.log('=== 系统诊断信息 ===');
        console.log('SockJS 库:', typeof SockJS !== 'undefined' ? '✓ 已加载' : '✗ 未加载');
        console.log('STOMP 旧版本:', typeof Stomp !== 'undefined' ? '✓ 已加载' : '✗ 未加载');
        console.log('STOMP 新版本:', typeof StompJs !== 'undefined' ? '✓ 已加载' : '✗ 未加载');
        console.log('浏览器:', navigator.userAgent);
        console.log('========================');
    }
    
    initializeElements() {
        this.personaList = document.getElementById('personaList');
        this.chatArea = document.getElementById('chatArea');
        this.messageInput = document.getElementById('messageInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.recordBtn = document.getElementById('recordBtn');
        this.audioPlayer = document.getElementById('audioPlayer');
    }
    
    bindEvents() {
        // 发送消息
        this.sendBtn.addEventListener('click', () => this.sendMessage());
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendMessage();
        });
        
        // 录音功能
        this.recordBtn.addEventListener('mousedown', () => this.startRecording());
        this.recordBtn.addEventListener('mouseup', () => this.stopRecording());
        this.recordBtn.addEventListener('mouseleave', () => this.stopRecording());
        
        // 角色选择
        this.personaList.addEventListener('click', (e) => {
            const personaItem = e.target.closest('.persona-item');
            if (personaItem) {
                this.selectPersona(personaItem.dataset.id);
            }
        });
    }
    
    async loadPersonas() {
        try {
            const response = await fetch('/api/personas');
            const personas = await response.json();
            this.renderPersonas(personas);
        } catch (error) {
            console.error('加载角色失败:', error);
            this.showError('加载角色失败');
        }
    }
    
    renderPersonas(personas) {
        this.personaList.innerHTML = '';
        personas.forEach(persona => {
            const personaDiv = document.createElement('div');
            personaDiv.className = 'persona-item';
            personaDiv.dataset.id = persona.id;
            personaDiv.innerHTML = `
                <div><strong>${persona.name}</strong></div>
                <div style="font-size: 12px; color: #666;">${persona.description}</div>
                <div style="margin-top: 5px;">
                    ${persona.skills.map(skill => `<span style="background: #e9ecef; padding: 2px 4px; border-radius: 3px; font-size: 10px; margin-right: 3px;">${skill}</span>`).join('')}
                </div>
            `;
            this.personaList.appendChild(personaDiv);
        });
    }
    
    async selectPersona(personaId) {
        try {
            // 清除之前的选择状态
            document.querySelectorAll('.persona-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 设置新的选择状态
            const selectedItem = document.querySelector(`[data-id="${personaId}"]`);
            if (selectedItem) {
                selectedItem.classList.add('active');
            }
            
            // 创建会话
            const response = await fetch('/api/chat/session', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    personaId: personaId,
                    preferredLanguage: 'zh-CN'
                })
            });
            
            if (!response.ok) {
                throw new Error('创建会话失败');
            }
            
            const sessionData = await response.json();
            this.sessionId = sessionData.sessionId;
            this.currentPersona = personaId;
            
            // 清空聊天区域
            this.chatArea.innerHTML = '';
            this.addMessage('assistant', `你好！我是${selectedItem.querySelector('strong').textContent}，很高兴与你对话！`);
            
            // 启用输入控件
            this.messageInput.disabled = false;
            this.sendBtn.disabled = false;
            this.recordBtn.disabled = false;
            
            // 连接WebSocket
            this.connectWebSocket();
            
        } catch (error) {
            console.error('选择角色失败:', error);
            this.showError('选择角色失败: ' + error.message);
        }
    }
    
    connectWebSocket() {
        // 延迟一下，确保库已加载
        setTimeout(() => {
            this.doConnectWebSocket();
        }, 100);
    }
    
    doConnectWebSocket() {
        try {
            // 检查依赖是否加载完成
            if (typeof SockJS === 'undefined') {
                throw new Error('SockJS 库未加载，请检查网络连接');
            }
            
            let stompAvailable = false;
            let stompVersion = '';
            let StompLib = null;
            
            // 优先使用旧版本（更稳定）
            if (typeof Stomp !== 'undefined') {
                stompAvailable = true;
                stompVersion = '旧版本 (v2.x)';
                StompLib = Stomp;
            } else if (typeof StompJs !== 'undefined') {
                stompAvailable = true;
                stompVersion = '新版本 (v7.x)';
                StompLib = StompJs.Stomp;
            }
            
            if (!stompAvailable || !StompLib) {
                throw new Error('STOMP 库未加载，请检查网络连接或刷新页面');
            }
            
            console.log(`开始建立WebSocket连接... (使用STOMP ${stompVersion})`);
            
            // 使用STOMP over WebSocket连接
            const socket = new SockJS('/ws/chat');
            
            // 使用检测到的STOMP库
            this.stompClient = StompLib.over(socket);
            
            // 启用调试信息(仅在旧版本中支持)
            if (typeof this.stompClient.debug === 'function') {
                this.stompClient.debug = (str) => {
                    console.log('STOMP Debug:', str);
                };
            }
        
            this.stompClient.connect({}, (frame) => {
                console.log('WebSocket连接已建立:', frame);
                
                // 订阅聊天主题
                this.stompClient.subscribe(`/topic/chat/${this.sessionId}`, (message) => {
                    const data = JSON.parse(message.body);
                    this.handleWebSocketMessage(data);
                });
                
                // 连接成功后启用相关功能
                this.enableChatFeatures();
                
            }, (error) => {
                console.error('WebSocket连接失败:', error);
                this.showError('连接失败，请检查服务器是否启动或刷新页面重试');
            });
            
        } catch (error) {
            console.error('WebSocket初始化失败:', error);
            this.showError('WebSocket初始化失败: ' + error.message);
            
            // 如果初始化失败，尝试重新加载
            if (error.message.includes('STOMP 库未加载')) {
                console.log('尝试重新加载 STOMP 库...');
                setTimeout(() => {
                    this.doConnectWebSocket();
                }, 2000);
            }
        }
    }
    
    enableChatFeatures() {
        // 启用聊天功能
        if (this.messageInput) {
            this.messageInput.disabled = false;
        }
        if (this.sendBtn) {
            this.sendBtn.disabled = false;
        }
        if (this.recordBtn) {
            this.recordBtn.disabled = false;
        }
        console.log('聊天功能已启用');
    }
    
    handleWebSocketMessage(message) {
        switch (message.type) {
            case 'PARTIAL_TEXT':
                // 如果是第一个文本块，先创建一个新的assistant消息
                if (!this.isReceivingResponse) {
                    this.addMessage('assistant', '');
                    this.isReceivingResponse = true;
                }
                this.appendToLastMessage(message.delta || message.content);
                break;
            case 'FINAL_TEXT':
                // 完整响应接收完毕
                this.isReceivingResponse = false;
                break;
            case 'AUDIO_CHUNK':
                this.playAudioChunk(message.data);
                break;
            case 'STATUS':
                if (message.content && message.content.startsWith('ASR识别:')) {
                    // 显示语音识别结果
                    console.log(message.content);
                }
                break;
            case 'ERROR':
                this.showError(message.content);
                this.isReceivingResponse = false;
                break;
        }
    }
    
    sendMessage() {
        const text = this.messageInput.value.trim();
        if (!text || !this.sessionId || !this.stompClient) return;
        
        this.addMessage('user', text);
        this.messageInput.value = '';
        
        // 通过WebSocket发送消息到后端
        const message = {
            type: 'USER_TEXT',  // 修复: 使用正确的枚举值
            text: text,
            timestamp: Date.now()
        };
        
        console.log('发送消息:', JSON.stringify(message));
        this.stompClient.send(`/app/chat/${this.sessionId}/text`, {}, JSON.stringify(message));
    }
    
    
    
    addMessage(type, content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        messageDiv.innerHTML = `<div>${content}</div>`;
        this.chatArea.appendChild(messageDiv);
        this.chatArea.scrollTop = this.chatArea.scrollHeight;
    }
    
    appendToLastMessage(text) {
        const lastMessage = this.chatArea.lastElementChild;
        if (lastMessage && lastMessage.classList.contains('assistant')) {
            const contentDiv = lastMessage.querySelector('div');
            contentDiv.textContent += text;
        }
    }
    
    async startRecording() {
        if (this.isRecording) return;
        
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            this.mediaRecorder = new MediaRecorder(stream);
            this.audioChunks = [];
            
            this.mediaRecorder.ondataavailable = (event) => {
                this.audioChunks.push(event.data);
            };
            
            this.mediaRecorder.onstop = () => {
                this.processRecording();
            };
            
            this.mediaRecorder.start();
            this.isRecording = true;
            this.recordBtn.textContent = '录音中...';
            this.recordBtn.style.background = '#ff4757';
            
        } catch (error) {
            console.error('录音启动失败:', error);
            this.showError('录音功能不可用');
        }
    }
    
    stopRecording() {
        if (!this.isRecording) return;
        
        this.mediaRecorder.stop();
        this.isRecording = false;
        this.recordBtn.textContent = '录音';
        this.recordBtn.style.background = '#dc3545';
        
        // 停止所有音频轨道
        this.mediaRecorder.stream.getTracks().forEach(track => track.stop());
    }
    
    async processRecording() {
        if (this.audioChunks.length === 0) return;
        
        try {
            const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
            const formData = new FormData();
            formData.append('audio', audioBlob, 'recording.wav');
            formData.append('language', 'zh-CN');
            
            const response = await fetch('/api/asr', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error('语音识别失败');
            }
            
            const result = await response.json();
            this.messageInput.value = result.text;
            
            // 自动发送识别的文本
            if (result.text.trim()) {
                this.sendMessage();
            }
            
        } catch (error) {
            console.error('处理录音失败:', error);
            this.showError('语音识别失败');
        }
    }
    
    playAudioChunk(base64Data) {
        try {
            const audioData = atob(base64Data);
            const arrayBuffer = new ArrayBuffer(audioData.length);
            const view = new Uint8Array(arrayBuffer);
            
            for (let i = 0; i < audioData.length; i++) {
                view[i] = audioData.charCodeAt(i);
            }
            
            const blob = new Blob([arrayBuffer], { type: 'audio/wav' });
            const audioUrl = URL.createObjectURL(blob);
            
            this.audioPlayer.src = audioUrl;
            this.audioPlayer.style.display = 'block';
            
            // 播放音频并处理可能的错误
            this.audioPlayer.play().then(() => {
                console.log('音频播放成功');
            }).catch(error => {
                console.warn('音频播放失败:', error.message);
                // 如果播放失败，可以尝试不同的MIME类型
                this.tryAlternativeAudioFormat(arrayBuffer);
            });
            
        } catch (error) {
            console.error('播放音频失败:', error);
        }
    }
    
    // 尝试替代音频格式
    tryAlternativeAudioFormat(arrayBuffer) {
        const alternativeTypes = ['audio/wav', 'audio/mp3', 'audio/ogg'];
        
        for (const mimeType of alternativeTypes) {
            try {
                const blob = new Blob([arrayBuffer], { type: mimeType });
                const audioUrl = URL.createObjectURL(blob);
                
                this.audioPlayer.src = audioUrl;
                this.audioPlayer.play().then(() => {
                    console.log(`使用 ${mimeType} 播放成功`);
                }).catch(() => {
                    // 继续尝试下一种格式
                });
                break;
            } catch (error) {
                // 继续尝试下一种格式
            }
        }
    }
    
    showError(message) {
        // 简单的错误显示
        alert(message);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new RoleplayApp();
});